package com.aierjun.myapplication;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.aierjun.ani.init.ImageLoaderUtils;
import com.aierjun.ani.init.LeakCanaryUtils;
import com.aierjun.ani.init.MultiDexUtils;
import com.aierjun.ani.init.OkGoUtils;
import com.aierjun.ani.init.UncaughtExceptionUtils;
import com.squareup.leakcanary.LeakCanary;

import java.util.LinkedList;
import java.util.List;


/**
 * Created by aierJun on 2017/1/5.
 */
public class MyApplication extends Application implements Thread.UncaughtExceptionHandler {

    private List activityList = new LinkedList();
    private static MyApplication application;
    // 提供一个单件


    //单例模式中获取唯一的ExitApplication实例
    public static   MyApplication getInstance() {
        return application;
    }
    //添加Activity到容器中
    public void addActivity(Activity activity)
    {
        for (int i=0;i<activityList.size();i++){
            if (activityList.get(i).getClass().getName().equals(activity.getClass().getName()))
                activityList.remove(activityList.get(i));
        }
        activityList.add(activity);
    }
    //遍历所有Activity并finish

    public void removeActivity(Activity activity){
        for (int i=0;i<activityList.size();i++){
            if (activityList.get(i).getClass().getName().equals(activity.getClass().getName()))
                activityList.remove(activityList.get(i));
        }
    }


    public Activity getTopActivity()
    {
        return (Activity) activityList.get(activityList.size()-1);
    }

    public void exit()
    {
        for(Object activity:activityList)
        {
            ((Activity) activity).finish();
        }
        activityList=null;
        System.exit(0);
        // 强制让应用退出
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        //异常处理
        UncaughtExceptionUtils.init(this);

        ImageLoaderUtils.init(this);

        OkGoUtils.init(this,null,null);
    }


    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        throwable.printStackTrace();
        UncaughtExceptionUtils.set(this,"AniLog",throwable);
    }





    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDexUtils.init(base);

    }

}
